﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jayden.Dll.BitTorrent
{
	public class BitField
	{
		private byte[] m_Bytes;
		private int m_Length;

		public BitField(int length)
		{
			m_Length = length;
			int trueLength = (int)Math.Ceiling(length / 8.0);
			m_Bytes = new byte[trueLength];
		}
		public BitField(int length, byte[] data, int offset, int count)
		{
			m_Length = length;
			m_Bytes = new byte[count];
			for (int c = 0; c < count; c++)
				m_Bytes[c] = data[offset + c];
		}

		public int Length { get { return m_Length; } }

		protected void Offset(int index, out int trueIndex, out int bitIndex, out byte filter)
		{
			trueIndex = index / 8;
			bitIndex = 7 - (index % 8);
			filter = (byte)(0x01 << bitIndex);
		}

		public bool this[int index]
		{
			get
			{
				int trueIndex, bitIndex;
				byte filter;
				Offset(index, out trueIndex, out bitIndex, out filter);
				return (m_Bytes[trueIndex] & filter) != 0;
			}
			set
			{
				int trueIndex, bitIndex;
				byte filter;
				Offset(index, out trueIndex, out bitIndex, out filter);
				if (value)
					m_Bytes[trueIndex] |= filter;
				else
					m_Bytes[trueIndex] &= (byte)(~filter);
			}
		}
	}
}
